package com.orange.core.service.merchant.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orange.core.service.merchant.MerchantService;
import com.orange.core.mapper.merchant.MerchantMapper;
import com.orange.core.pojo.PageReqDto;
import com.orange.core.pojo.entity.merchant.Merchant;
import com.orange.core.pojo.entity.merchant.dto.MerchantDTO;
import com.orange.core.pojo.entity.merchant.vo.MerchantVO;
import com.orange.core.pojo.req.merchant.MerchantPageReq;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>ClassName:MerchantServiceImpl</p>
 * <p>Description: 社区服务管理-商家信息impl</p>
 * <p>Author: lwm</p>
 * <p>Date: 2025/5/22 15:23</p>
 */
@Service
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> implements MerchantService {


    @Override
    public Page<MerchantVO> page(PageReqDto<MerchantPageReq> pageReqDto) {
        String name = Optional.ofNullable(pageReqDto.getCondition()).map(MerchantPageReq::getName).orElse(null);
        Page<Merchant> page = this.lambdaQuery().like(StrUtil.isNotBlank(name), Merchant::getName, name)
                .orderByDesc(Merchant::getId)
                .page(pageReqDto.toPage());

        Page<MerchantVO> merchantVOPage = new Page<>(pageReqDto.getPage(), pageReqDto.getSize(), page.getTotal());
//        List<MerchantVO> merchantVOList = ConvertUtils.convertListToVo(page.getRecords(), MerchantVO.class);
        List<MerchantVO> merchantVOList = page.getRecords().stream().map(MerchantVO::objToVo).collect(Collectors.toList());
        merchantVOPage.setRecords(merchantVOList);
        return merchantVOPage;
    }

    @Override
    public MerchantVO info(int id) {
        Merchant merchant = this.getById(id);
        Assert.notNull(merchant, "商家不存在");
        MerchantVO merchantVO = MerchantVO.objToVo(merchant);
        return merchantVO;
    }


    @Override
    @Transactional
    public boolean save(MerchantDTO merchantDTO) {
        Merchant merchant = new Merchant();
        BeanUtil.copyProperties(merchantDTO, merchant);
        boolean result = this.save(merchant);
        return result;
    }

    @Override
    @Transactional
    public boolean  update(MerchantDTO merchantDTO) {
        Merchant merchant = new Merchant();
        BeanUtil.copyProperties(merchantDTO, merchant);
        boolean result = this.updateById(merchant);
        return result;
    }

    @Override
    @Transactional
    public boolean deleteMerchantByIds(Integer[] ids) {
        boolean result = this.removeBatchByIds(Arrays.asList(ids));
        return result;
    }
}
